//
//  AssetDetailsViewController.m
//  NiuBanJinGold
//
//  Created by Billy on 15/10/19.
//  Copyright © 2015年 zzjr. All rights reserved.
//

// 关于本页面的刷新功能 的说明:
//第一次进去做一次自动的下拉刷新,其它的button,做一个点击刷新功能，然后所有的都加上下拉刷新功能


#import "AssetDetailsViewController.h"
#import "BCSwitchView.h"
#import "AssetList.h"
#import "AssetListViewCell.h"

@interface AssetDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,BCSwitchViewDelegate>

@property (nonatomic, strong) BCSwitchView *view_header;
@property (nonatomic, strong) UIView *view_sep;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *mutableArray_data; //数据源，存放AssetList Object

@property (nonatomic, strong) NSDictionary *dic_params ;// 当前页面共用的一个访问参数列表
@property(nonatomic, copy) NSString *str_assetType; // 1：全部，2：存入，3：收益，4：转出

@property(nonatomic, assign) int pageNumber; // 当前访问的页数
@property(nonatomic, assign) int footerFreshPageNumbr; // 当前访问的页数


@end

@implementation AssetDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self.navigationItem setTitle:@"帐户明细"];
    
    [self.view addSubview:self.view_header];
    [self.view addSubview:self.view_sep];
    [self.view addSubview:self.tableView];
    
    // 初始化访问页数
    
    self.pageNumber = 1; //默认只访问第一页，上拉刷新时会做++操作，下拉刷新的时候会恢复成1
    self.str_assetType = @"1"; //默认访问全部list
}

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self getDataFromServer];
    
    [self buttonSelected:[self.view_header viewWithTag:100]]; //BUG 251,每次出现该页面，自动显示未使用的
}

- (void) setupFresh {
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
//    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

// 下拉刷新

- (void) headerRefresh {
    
    self.pageNumber = 1; //刷新恢复 成默认值
    [self getDataFromServer];
}

// 上拉刷新

- (void) footerRefresh {
    
    self.pageNumber++;
    [self getDataFromServer];
}

// 真实的数据访问
- (void) getDataFromServer {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.labelText = @"正在加载";
    
    [[NetworkUtil sharedNetworkUtil] zzjrUserAssetsListByParmeteres:self.dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [hud hide:YES];
        
        [self.tableView.header endRefreshing]; //停止刷新
        [self.tableView.footer endRefreshing];
        
        if (!error) {
            
            //得到数据后做刷新操作
            // 因为有下拉刷新，所以这儿不能光想着clear ,按pageNumber来区分，如果大于2表明有下拉刷新要保存历史记录
            
            if (self.pageNumber > 1) { //保存历史数据
                
                [self.mutableArray_data addObjectsFromArray:parsedData];
                
            } else {
                
                self.mutableArray_data = parsedData;
                // 如果得到的数据为空。显示为暂无数据
                
                if ([self.mutableArray_data count] == 0) {
                    
                    EmptyDataView *view_empty = [[EmptyDataView alloc]initWithFrame:self.tableView.frame];
                    [self.view addSubview:view_empty]; // 加过一次后就永远存在了，要想办法去掉
                }else {
                    
                    [self.view bringSubviewToFront:self.tableView]; //把tableview放前面就行了，不用remove再加,省资源
                }
            }

            [self.tableView reloadData];

        }else {
            
            [self.tableView.header endRefreshing]; //停止刷新
            [self.tableView.footer endRefreshing];
            [UsefulUtil showAlertView:@"遇到网络问题，请稍候重试!"]; //现阶段直接把错误详情展示出来
        }
    }];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_data count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(100.0/2)];
    
    static NSString *identifer = @"cellAssetList" ;
    
    AssetListViewCell *cell = (AssetListViewCell *)[tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[AssetListViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifer];
    }
    
    [cell setAssetList:self.mutableArray_data[indexPath.row]];
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - button events handling

- (void) buttonSelected:(UIButton *) button {
    
    [button setTitleColor:REDCOLOR forState:UIControlStateNormal];
    
    switch (button.tag) {
            
        case 100: //全部
        {
            NSLog(@"全部");
            self.str_assetType  =@"1";
            [self getDataFromServer];
            
            for (UIView *tmp in self.view_header.subviews) {
                
                if ([tmp isMemberOfClass:[UIButton class]] && tmp.tag != 100) {
                    
                    [((UIButton *) tmp) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];

                }
            }

        }
            break;
            
        case 101: //存入
        {
            NSLog(@"存入");
            self.str_assetType  =@"2";
            self.pageNumber = 1; //这儿把页数设为1的原因是防止全部点过上拉刷新，让pageNumber变成2， 这样的话进入存入点上拉刷新的话就会从3开始走,下面reason same
            [self getDataFromServer];
            
            for (UIView *tmp in self.view_header.subviews) {
                
                if ([tmp isMemberOfClass:[UIButton class]] && tmp.tag != 101) {
                    
                    [((UIButton *) tmp) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
                    
                }
            }
        }
            break;
            
        case 102: //收益
        {
            NSLog(@"收益");
            self.str_assetType  =@"3";
            self.pageNumber = 1;
            [self getDataFromServer];
            
            for (UIView *tmp in self.view_header.subviews) {
                
                if ([tmp isMemberOfClass:[UIButton class]] && tmp.tag != 102) {
                    
                    [((UIButton *) tmp) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
                    
                }
            }
        }
            break;
            
        case 103://转出
            
        {
            NSLog(@"转出");
            self.str_assetType  =@"4";
            self.pageNumber = 1;
            [self getDataFromServer];
            
            for (UIView *tmp in self.view_header.subviews) {
                
                if ([tmp isMemberOfClass:[UIButton class]] && tmp.tag != 103) {
                    
                    [((UIButton *) tmp) setTitleColor:[UsefulUtil colorWithHexString:@"#434343"] forState:UIControlStateNormal];
                    
                }
            }
        }
            break;
            
        default:

            break;
    }
}

#pragma mark - setter methods

- (BCSwitchView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [[BCSwitchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(100.0/2)) Items:@[@"全部",@"存入",@"收益",@"转出"] ];
        [_view_header setColor_scroll:REDCOLOR];
//        [_view_header setColor_title:REDCOLOR];
        
        [_view_header setDelegate:self];
    }
    
    return  _view_header;
}

- (UIView *)view_sep {
    
    if (!_view_sep) {
        
        _view_sep = [UsefulUtil viewCreationWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_header.frame), SCREEN_HEIGHT, MULTIPLYHEIGHT(2.0/2)) backgroundColor:[UsefulUtil colorWithHexString:@"#C8C7CC"] backGroundImage:nil];
    }
    
    return _view_sep;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_sep.frame), SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(self.view_header.frame)) style:UITableViewStylePlain];
        
        [_tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setAllowsSelection:NO];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView setTableFooterView:view];
    }
    
    return  _tableView;
}

- (NSMutableArray *)mutableArray_data {
    
    if (!_mutableArray_data) {
        
        _mutableArray_data = [NSMutableArray array];
    }
    
    return _mutableArray_data;
}

#pragma mark - parameteres of accessing

- (NSDictionary *)dic_params {
        
    return  @{@"userId":GETCURRENTUSERINOBYPRAMETERES(user_userId),@"type":self.str_assetType,@"pageNum":[NSString stringWithFormat:@"%d",self.pageNumber]};
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
